package com.zzzzzz.core.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;

@Controller
public class FileController {
	
	@Resource
	private Mongo mongo;
	@Resource
	private Environment environment;
	
	@RequestMapping(value = "/image/{id}", method = RequestMethod.GET)
	public void imageView(@PathVariable String id,HttpServletResponse response) throws IOException {
		String fileDbName = environment.getProperty("mongo.file_dbname");
		DB db = mongo.getDB(fileDbName);
		GridFS gfsFile = new GridFS(db);
		GridFSDBFile fileOut = gfsFile.findOne(new ObjectId(id));
		response.setContentType("utf-8");
		InputStream is = fileOut .getInputStream();
		int read = 0;
		byte[] bytes = new byte[1024];
		OutputStream os = response.getOutputStream();
		while((read = is.read(bytes)) != -1) {
			os.write(bytes, 0, read);
		}
		os.flush();
		os.close();
	}
}
